import { createFileRoute } from '@tanstack/react-router'
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from "@/components/ui/card"
import { api } from '@/lib/api'
import { useQuery } from '@tanstack/react-query'

export const Route = createFileRoute('/_authenticated/')({
    component: Index,
})

async function getTotalSpent() {
    const res = await api.expenses['total-spent'].$get()
    if (!res.ok) {
        throw new Error('Failed to fetch total spent')
    }
    return res.json()
}

function Index() {
    const { isPending, error, data } = useQuery({
        queryKey: ['total-spent'],
        queryFn: getTotalSpent,
    })

    if (error) return 'Error fetching total spent'

    return (
        <>
            <Card>
                <CardHeader>
                    <CardTitle>Total Spent</CardTitle>
                    <CardDescription>The total amount you've spent</CardDescription>
                </CardHeader>
                <CardContent>
                    {isPending ? 'Loading...' : data.total}
                </CardContent>
            </Card>
        </>
    )
}

